<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>代码生成器</title>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/css/bootstrap-icons.css}" rel="stylesheet">
    <style>
        :root {
            --bs-primary: #3f51b5;
            --bs-primary-rgb: 63, 81, 181;
            --bs-secondary: #6c757d;
        }
        body {
            background-color: #f8f9fa;
        }
        .main-container {
            max-width: 1300px;
            margin: 0 auto;
            padding: 30px 20px;
        }
        .code-area {
            font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
            font-size: 14px;
            min-height: 300px;
            border-radius: 8px;
            border-color: #ddd;
            box-shadow: inset 0 1px 3px rgba(0,0,0,.05);
        }
        .form-card {
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,.05);
            overflow: hidden;
            border: none;
        }
        .card-header-custom {
            background-color: var(--bs-primary);
            color: white;
            padding: 16px 20px;
            font-size: 1.2rem;
        }
        .btn-primary {
            background-color: var(--bs-primary);
            border-color: var(--bs-primary);
        }
        .btn-primary:hover {
            background-color: #303f9f;
            border-color: #303f9f;
        }
        .example-panel {
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,.05);
            margin-top: 30px;
            padding: 20px;
        }
        .example-code {
            background-color: #f6f8fa;
            border-radius: 8px;
            padding: 15px;
            font-size: 14px;
            max-height: 350px;
            overflow-y: auto;
            white-space: pre;
            font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
        }
        .option-toggle {
            cursor: pointer;
            user-select: none;
        }
        .help-text {
            font-size: 0.9rem;
            color: #6c757d;
        }
        .form-label {
            font-weight: 500;
        }
        .feature-icon {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 40px;
            height: 40px;
            border-radius: 8px;
            background-color: #e9e9ff;
            color: var(--bs-primary);
            margin-bottom: 10px;
        }
        .preview-container {
            background-color: #f5f5f5;
            border-radius: 8px;
            padding: 15px;
            margin-top: 15px;
            display: none;
        }
        .preview-title {
            font-weight: 500;
            margin-bottom: 10px;
        }
        .preview-content {
            font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
            font-size: 13px;
            background-color: #fff;
            border-radius: 6px;
            padding: 12px;
            max-height: 250px;
            overflow-y: auto;
        }
        .preview-table {
            border-collapse: collapse;
            width: 100%;
        }
        .preview-table th, .preview-table td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
        }
        .preview-table th {
            background-color: #f0f0f0;
        }
    </style>
</head>
<body>
    <div class="main-container">
        <div class="text-center mb-4">
            <h1 class="display-5 fw-bold mb-2">代码生成器</h1>
            <p class="fs-5 text-secondary">根据数据库表结构自动生成符合最佳实践的全套代码</p>
        </div>
        
        <div th:if="${errorMessage}" class="alert alert-danger d-flex align-items-center mb-4" role="alert">
            <i class="bi bi-exclamation-triangle-fill me-2"></i>
            <div th:text="${errorMessage}"></div>
        </div>
        
        <div class="card form-card mb-4">
            <div class="card-header-custom d-flex align-items-center">
                <i class="bi bi-code-slash me-2"></i> 代码生成表单
            </div>
            <div class="card-body p-4">
                <form method="post" th:object="${input}" class="needs-validation" novalidate>
                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label for="packagePrefix" class="form-label">
                                <i class="bi bi-folder me-1"></i> 包名前缀
                            </label>
                            <div class="input-group">
                                <span class="input-group-text bg-light">com.</span>
                                <input type="text" class="form-control" id="packagePrefix" th:field="*{packagePrefix}" 
                                    placeholder="example.project" required>
                            </div>
                            <div class="invalid-feedback">请输入有效的包名前缀</div>
                            <div class="form-text">例如：example.project</div>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="frameworkType" class="form-label">
                                <i class="bi bi-diagram-3 me-1"></i> 架构类型
                            </label>
                            <select class="form-select" id="frameworkType" th:field="*{frameworkType}">
                                <option value="SPRING_BOOT">Spring Boot 3.3.0 架构</option>
                                <option value="COLA">COLA 架构</option>
                            </select>
                            <div class="form-text">选择要生成的代码架构类型</div>
                        </div>
                    </div>
                    
                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label for="specialRequirements" class="form-label">
                                <i class="bi bi-gear me-1"></i> 特殊需求（可选）
                            </label>
                            <input type="text" class="form-control" id="specialRequirements" th:field="*{specialRequirements}" 
                                placeholder="例如：需要添加审计日志功能">
                            <div class="form-text">指定任何特殊业务规则或定制需求</div>
                        </div>
                    </div>
                    
                    <div class="mb-4">
                        <label for="ddlSql" class="form-label d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-database me-1"></i> DDL SQL语句</span>
                            <button type="button" id="previewBtn" class="btn btn-sm btn-outline-primary" onclick="previewDDL()">
                                <i class="bi bi-eye me-1"></i> 预览表结构
                            </button>
                        </label>
                        <textarea class="form-control code-area" id="ddlSql" th:field="*{ddlSql}" rows="12" 
                            placeholder="请输入包含一个或多个表的完整DDL语句" required></textarea>
                        <div class="invalid-feedback">请输入DDL SQL语句</div>
                        <div class="form-text">
                            <i class="bi bi-info-circle me-1"></i> 您可以一次性输入多个CREATE TABLE语句，系统将解析并为每个表生成相应代码
                        </div>
                        
                        <!-- 表结构预览容器 -->
                        <div class="preview-container" id="previewContainer">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <div class="preview-title"><i class="bi bi-table me-2"></i>表结构预览</div>
                                <button type="button" class="btn-close" onclick="closePreview()"></button>
                            </div>
                            <div class="preview-content" id="previewContent">
                                <!-- 预览内容将通过JavaScript动态生成 -->
                            </div>
                        </div>
                    </div>
                    
                    <div class="row g-3 mb-2">
                        <div class="col-md-4">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" value="true" id="generateTests" name="generateTests" checked>
                                <label class="form-check-label" for="generateTests">
                                    <i class="bi bi-check2-circle me-1"></i> 生成单元测试代码
                                </label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" value="true" id="generateComments" name="generateComments" checked>
                                <label class="form-check-label" for="generateComments">
                                    <i class="bi bi-chat-text me-1"></i> 生成详细注释
                                </label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" value="true" id="generateSwagger" name="generateSwagger" checked>
                                <label class="form-check-label" for="generateSwagger">
                                    <i class="bi bi-file-earmark-text me-1"></i> 添加Swagger文档
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
                        <button type="reset" class="btn btn-light px-4 me-md-2">
                            <i class="bi bi-arrow-counterclockwise me-1"></i> 重置
                        </button>
                        <button type="submit" class="btn btn-primary px-4">
                            <i class="bi bi-lightning me-1"></i> 生成代码
                        </button>
                    </div>
                </form>
            </div>
        </div>
        
        <div class="example-panel">
            <h4 class="mb-4"><i class="bi bi-journal-text me-2"></i>功能说明</h4>
            
            <div class="row g-4 mb-4">
                <div class="col-md-4">
                    <div class="feature-icon">
                        <i class="bi bi-layers"></i>
                    </div>
                    <h5>多种架构支持</h5>
                    <p class="text-muted">支持生成Spring Boot 3.3.0最佳实践架构或COLA架构的代码</p>
                </div>
                <div class="col-md-4">
                    <div class="feature-icon">
                        <i class="bi bi-table"></i>
                    </div>
                    <h5>多表同时处理</h5>
                    <p class="text-muted">支持在一次操作中解析多个表结构，同时生成多个实体的完整代码</p>
                </div>
                <div class="col-md-4">
                    <div class="feature-icon">
                        <i class="bi bi-code-square"></i>
                    </div>
                    <h5>完整代码结构</h5>
                    <p class="text-muted">生成包括控制器、服务、仓库、实体类在内的全套代码架构</p>
                </div>
            </div>
            
            <h5 class="mt-4 mb-3"><i class="bi bi-code me-2"></i>示例DDL：</h5>
            <div class="example-code">CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `username` varchar(64) NOT NULL COMMENT '用户名',
  `password` varchar(64) NOT NULL COMMENT '密码',
  `real_name` varchar(64) DEFAULT NULL COMMENT '真实姓名',
  `phone` varchar(20) DEFAULT NULL COMMENT '手机号',
  `email` varchar(64) DEFAULT NULL COMMENT '邮箱',
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态：0-禁用，1-启用',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';

CREATE TABLE `role` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '角色ID',
  `role_name` varchar(64) NOT NULL COMMENT '角色名称',
  `role_code` varchar(64) NOT NULL COMMENT '角色编码',
  `description` varchar(128) DEFAULT NULL COMMENT '角色描述',
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态：0-禁用，1-启用',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_role_code` (`role_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色表';</div>
        </div>
    </div>
    
    <script th:src="@{/js/bootstrap.bundle.min.js}"></script>
    <script>
        // 表单验证
        (function() {
            'use strict'
            var forms = document.querySelectorAll('.needs-validation')
            Array.prototype.slice.call(forms).forEach(function(form) {
                form.addEventListener('submit', function(event) {
                    if (!form.checkValidity()) {
                        event.preventDefault()
                        event.stopPropagation()
                    }
                    form.classList.add('was-validated')
                }, false)
            })
            
            // 自动处理包名前缀
            document.getElementById('packagePrefix').addEventListener('input', function(e) {
                let value = e.target.value;
                if (value.startsWith('com.')) {
                    e.target.value = value.substring(4);
                }
            });
        })()
        
        // 预览DDL表结构
        function previewDDL() {
            const ddlSql = document.getElementById('ddlSql').value;
            if (!ddlSql) {
                alert('请先输入DDL SQL语句');
                return;
            }
            
            // 显示预览容器
            document.getElementById('previewContainer').style.display = 'block';
            document.getElementById('previewContent').innerHTML = '<div class="spinner-border spinner-border-sm text-primary" role="status"><span class="visually-hidden">Loading...</span></div> 正在解析表结构...';
            
            // 简单解析表结构的正则表达式
            const tablePattern = /CREATE\s+TABLE\s+`(\w+)`\s*\(([\s\S]*?)\)\s*ENGINE/gi;
            const columnPattern = /`(\w+)`\s+(\w+(?:\(\d+(?:,\d+)?\))?)\s*(NOT\s+NULL)?\s*(DEFAULT\s+[^,]+)?\s*(?:COMMENT\s*'([^']*)')?[,]?/gi;
            
            let tables = [];
            let match;
            
            // 查找所有表
            while ((match = tablePattern.exec(ddlSql)) !== null) {
                const tableName = match[1];
                const columnsDefinition = match[2];
                
                let columns = [];
                let columnMatch;
                
                // 查找所有列
                const columnRegex = new RegExp(columnPattern);
                while ((columnMatch = columnRegex.exec(columnsDefinition)) !== null) {
                    columns.push({
                        name: columnMatch[1],
                        type: columnMatch[2],
                        notNull: columnMatch[3] ? true : false,
                        defaultValue: columnMatch[4] ? columnMatch[4].replace('DEFAULT ', '') : '',
                        comment: columnMatch[5] || ''
                    });
                }
                
                tables.push({
                    name: tableName,
                    columns: columns
                });
            }
            
            // 生成预览HTML
            if (tables.length > 0) {
                let html = '';
                tables.forEach(table => {
                    html += `<div class="mb-4">
                        <h6 class="mb-2"><i class="bi bi-table me-1"></i>${table.name}</h6>
                        <table class="preview-table">
                            <thead>
                                <tr>
                                    <th>列名</th>
                                    <th>类型</th>
                                    <th>是否必填</th>
                                    <th>默认值</th>
                                    <th>注释</th>
                                </tr>
                            </thead>
                            <tbody>`;
                    
                    table.columns.forEach(col => {
                        html += `<tr>
                            <td>${col.name}</td>
                            <td>${col.type}</td>
                            <td>${col.notNull ? '是' : '否'}</td>
                            <td>${col.defaultValue}</td>
                            <td>${col.comment}</td>
                        </tr>`;
                    });
                    
                    html += `</tbody>
                        </table>
                    </div>`;
                });
                
                document.getElementById('previewContent').innerHTML = html;
            } else {
                document.getElementById('previewContent').innerHTML = '<div class="alert alert-warning mb-0">无法解析表结构，请检查DDL语法是否正确</div>';
            }
        }
        
        // 关闭预览
        function closePreview() {
            document.getElementById('previewContainer').style.display = 'none';
        }
    </script>
</body>
</html>